package edu.lingnan.librarymanage.repository;

import edu.lingnan.librarymanage.core.bean.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author cql
 */
@Repository
public interface CategoryRepository extends JpaRepository<Category, Integer> {


    /**
     * 根据名字查询分类
     *
     * @param name
     * @return
     */
    @Query(value = "select * from category where name = :name", nativeQuery = true)
    Category findByName(@Param("name") String name);

    /**
     * 查找该分类下的所有子分类
     *
     * @param categoryId
     * @return
     */
    @Query(value = "select * from category where parent_id = :categoryId", nativeQuery = true)
    List<Category> findByParent(@Param("categoryId") Integer categoryId);

    /**
     * 更新分类
     *
     * @param categoryId
     * @param name
     */
    @Transactional
    @Modifying
    @Query(value = "update category set name = :name where category_id = :categoryId", nativeQuery = true)
    void updateCategory(@Param("categoryId") Integer categoryId, @Param("name") String name);
}
